//
//  TRUploadEditerViewController.m
//  WeiMiLan
//
//  Created by anan on 15/2/4.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "TRUploadEditerViewController.h"
#import "CDPEmojiKeyBoard.h"

#import "TYAttributedLabel.h"
#import "TYImageStorage.h"
#import "TYTextStorage.h"

#import "FastTextView.h"
#import "SlideAttachmentCell.h"
#import <QuartzCore/QuartzCore.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "UIImage-Extensions.h"
#import "NSAttributedString+TextUtil.h"
#import "TextConfig.h"
#import "AGIPCToolbarItem.h"


#import "AssetsPickerDeepCustomDemoViewController.h"
#import "DeepCustomStyle.h"
#import "GJCFAssetsPickerViewController.h"
#import "TVGDebugQuickUI.h"
#import "CustomAlbumsCell.h"
#import "GJCFUitils.h"

//#import "RegexKitLite.h"


@interface TRUploadEditerViewController ()<CDPEmojiKeyboardDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
   
    NSInteger _currentKeyboardMode;//当前表情键盘的模式
}
@property (nonatomic, strong) CDPEmojiKeyBoard *emojiKeyBoard;//emoji键盘
@property (strong, nonatomic) AGImagePickerController *ipc;
@property (weak, nonatomic) IBOutlet UIButton *emojiBtn;
@property (nonatomic,strong)NSMutableArray *currentSelectedAssetsArray;
@end

@implementation TRUploadEditerViewController

- (IBAction)emojiButtonClick:(UIButton *)sender {
    if (self.emojiKeyBoard.isAppear==NO) {
        //emoji键盘出现
        [self.emojiKeyBoard keyboardAppear];
        //self.emojiKeyBoard.keyboardHeight = 178;
    }
    else{
        //切换为系统键盘出现
        if(_currentKeyboardMode==0){
            //第一种模式
            [self.emojiKeyBoard keyboardDisAppear];
            [self.contentTextView becomeFirstResponder];
        }
        else{
            //第二种模式
            [self.contentTextView becomeFirstResponder];
        }
    }
    
}
//点击视图空白处
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //emoji键盘消失
    [self.emojiKeyBoard keyboardDisAppear];
    [self.contentTextView resignFirstResponder];
    //结束输入状态
    [self.view endEditing:YES];
    
}

#pragma mark CDPEmojiKeyboardDelegate
//emoji键盘出现
-(void)didWhenKeyboardAppear{
    [self.emojiBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-biaoqing-(1)"] forState:UIControlStateNormal];
}
//emoji键盘消失
-(void)didWhenKeyboardDisappear{
    [self.emojiBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-biaoqing-(1)"] forState:UIControlStateNormal];
}
#pragma mark 模式2情况下才会执行的方法(可选)
//系统键盘出现
-(void)didWhenSystemKeyboardAppear:(NSNotification *)notification{
    [self.emojiBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-biaoqing-(1)"] forState:UIControlStateNormal];
    NSLog(@"系统键盘出现");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.currentSelectedAssetsArray = [[NSMutableArray alloc]init];
    self.images = [[NSMutableArray alloc] init];
    self.photoDeletes = [[NSMutableArray alloc] init];
    self.photoUpdates = [[NSMutableArray alloc] init];
    self.photoUploads = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    
    __block TRUploadEditerViewController *blockSelf = self;
    
    self.ipc = [AGImagePickerController sharedInstance:self];
//    self.ipc.didFailBlock = ^(NSError *error) {
//        NSLog(@"Fail. Error: %@", error);
//        
//        if (error == nil) {
//            [blockSelf.images removeAllObjects];
//            NSLog(@"User has cancelled.");
//            
//            [blockSelf dismissViewControllerAnimated:YES completion:nil];
//        } else {
//            
//            // We need to wait for the view controller to appear first.
//            double delayInSeconds = 0.5;
//            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                [blockSelf dismissViewControllerAnimated:YES completion:nil];
//            });
//        }
//        
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
//        
//    };
//    self.ipc.didFinishBlock = ^(NSArray *info) {
//       // [blockSelf.images setArray:info];
//        
//        NSLog(@"Info: %@", info);
//        
//        for (int i=0; i<info.count; i++) {
//            //        ALAsset *asset=assets[i];
//            //        NSString *fileName = asset.defaultRepresentation.filename;
//            //        UIImage *image=[UIImage imageWithCGImage:asset.defaultRepresentation.fullResolutionImage];
//            //        [self.images addObject:@{@"image": image,@"name":fileName}];
//            //   提取原图
//            ALAsset *ii=info[i];
//            ALAssetRepresentation *assetRep = [ii defaultRepresentation];
//            CGImageRef imgRef = [assetRep fullResolutionImage];
//            UIImage *image = [UIImage imageWithCGImage:imgRef
//                                                 scale:assetRep.scale
//                                           orientation:(UIImageOrientation)assetRep.orientation];
//            
//            NSString *fileName = assetRep.filename;
//            
//            
//            if (blockSelf.images.count<9) {
//                [blockSelf.images addObject:@{@"image": image,@"name":fileName}];
//            }else{
//                //                MMProgressHUDShowError(@"最多不超过9张");
//                [SVProgressHUD showImage:nil status:@"最多不超过9张"];
//            }
//            
//        }
//        [blockSelf.collectionView reloadData];
//        
//        
//        
//        [blockSelf dismissViewControllerAnimated:YES completion:nil];
//        
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
//    };
    
    
    
    [self initNavigation];
    
    //设置键盘模式(0或1)
    _currentKeyboardMode=1;
    
    //创建emoji键盘
    self.emojiKeyBoard=[[CDPEmojiKeyBoard alloc] initWithInputView:self.contentTextView andSuperView:self.view yOfScreenBottom:self.view.bounds.size.height keyboardMode:_currentKeyboardMode];
    self.emojiKeyBoard.delegate=self;
    
    
    [self loadTypes];
    
    
    
    UINib *nib = [UINib nibWithNibName:@"TRImageItemCollectionViewCell" bundle:[NSBundle mainBundle]];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:@"TRImageItemCollectionViewCell"];
    
    self.viewRecord2.hidden = YES;
    self.labelRecordHint.hidden = YES;
    
    if (self.productTypeId) {
        self.viewRecord1.hidden = NO;
        self.viewRecord2.hidden = YES;
        self.viewAskBuy.hidden = YES;
    }
    
    AVAudioSession* r = [AVAudioSession sharedInstance];
    NSError* sessionError;
    [r setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if(recorder == nil)
        NSLog(@"Error creating session: %@", [sessionError description]);
    else
        [r setActive:YES error:nil];
    
    
}

-(void)startRecord {
    if (self.isPlaying) {
        return;
    }
    if (!self.isRecording) {
        self.isRecording = YES;
        [RecorderManager sharedManager].delegate = self;
        [[RecorderManager sharedManager] startRecording];
        self.timeStart = [NSDate date].timeIntervalSince1970;
    }
    else {
        self.isRecording = NO;
        [[RecorderManager sharedManager] stopRecording];
    }
}


-(void)stopRecord {
    self.timeEnd = [NSDate date].timeIntervalSince1970;
    self.isRecording = NO;
    [[RecorderManager sharedManager] stopRecording];
    self.viewRecord2.hidden = NO;
    self.recorderLength = self.timeEnd - self.timeStart;
    self.labelRecordLength.text = [NSString stringWithFormat:@"%d'",(int)self.recorderLength];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(uploadResult:)
                                                 name: @"UPLOAD_SUCCESS"
                                               object: nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UPLOAD_SUCCESS" object:nil];
    if (timer) {
        [timer invalidate];
    }
}


- (void)uploadResult:(NSNotification *)note
{
    NSString *str = note.object;
    if ([str isEqualToString:@"success"]) {
        NSData *data = [NSData dataWithContentsOfURL:urlPlay];
        if (data) {
            [self uploadRecord:paramDict];
            return;
        }
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
    }
}


- (void)setProductTypeId:(NSString *)productTypeId
{
    _productTypeId = productTypeId;
    [self loadProductDetail];
}

- (void)loadProductDetail
{
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [ApplicationDelegate.webAPI getWebAPIWithParams:@{@"type":SERVICE_CODE_PRODUCT_PREVIEW,PRODUCT_TYPE_ID:self.productTypeId?self.productTypeId:@""} andMethodNode:NODE_PRODUCT completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        if (state==1) {
            ApplicationDelegate.shareContent=responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"][@"DESCRIPTION"];
            self.productInfo = responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"];
            
            NSArray *imgs = responseObject[@"PRODUCT_RSP"][@"PRODUCT"];
            if (imgs&&imgs.count>0) {
                NSDictionary *dic = [imgs firstObject];
                self.productNameOld = [dic ql_stringForKey:@"NAME"];
                self.productNameOld = [[self.productNameOld componentsSeparatedByString:@"_IMG_"] firstObject];
            }
                    
            NSString* code = responseObject[@"MESSAGE_INFO"][@"CODE"];
            NSString* message=responseObject[@"MESSAGE_INFO"][@"MESSAGE"];
            
            if ([code isEqualToString:@"0000"]) {
                self.imagesService = responseObject[@"PRODUCT_RSP"][@"PRODUCT"];
                NSDictionary *dic =responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"];
                self.productInfo = dic;
                self.textFieldPrize.text = self.productInfo[@"PRICE"];
                self.contentTextView.text = self.productInfo[@"DESCRIPTION"];
                
                if ([self.productInfo ql_hasObjectForKey:@"TYPE_NAME"]) {
                    NSString *name = [dic ql_stringForKey:@"TYPE_NAME"];
                    for (NSDictionary *tmp in self.directorys) {
                        if (name&&[name isEqualToString:tmp[@"NAME"]]) {
                            [self.buttonType setTitle:tmp[@"NAME"] forState:UIControlStateNormal];
                        }
                    }
                }
                
                for (NSDictionary *tmp in self.imagesService) {
                    NSMutableDictionary *imgInfo = [[NSMutableDictionary alloc] initWithDictionary:tmp];
                    [self.images addObject:imgInfo];
                }
                [self.collectionView reloadData];
            }else{
                [SVProgressHUD showImage:nil status:message];
            }
        }
    }];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    
    self.weChatNavigationBar.titleLabel.text=@"发表内容";
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(exitHomePage) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.leftButton.hidden = NO;
    self.weChatNavigationBar.rightButton.hidden = NO;
    [self.weChatNavigationBar.rightButton setBackgroundImage:nil forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton setImage:nil forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton setTitle:@"发送" forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(buttonSubmitAction:) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.weChatNavigationBar.rightButton sizeToFit];
    
    if (self.productTypeId) {
        self.weChatNavigationBar.rightButton2.hidden = NO;
        [self.weChatNavigationBar.rightButton2 setBackgroundImage:nil forState:UIControlStateNormal];
        [self.weChatNavigationBar.rightButton2 setImage:nil forState:UIControlStateNormal];
        [self.weChatNavigationBar.rightButton2 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [self.weChatNavigationBar.rightButton2 setImage:nil forState:UIControlStateHighlighted];
        [self.weChatNavigationBar.rightButton2 setTitle:@"删除" forState:UIControlStateNormal];
        [self.weChatNavigationBar.rightButton2 addTarget:self action:@selector(buttonProductDeleteAction:) forControlEvents:UIControlEventTouchUpInside];
        self.weChatNavigationBar.rightButton2.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.weChatNavigationBar.rightButton2 sizeToFit];

    }
    

}

- (void)buttonProductDeleteAction:(id)sender
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除这个上传？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
    alertView.tag = 1;
    [alertView show];
}

- (void)buttonSubmitAction:(id)sender
{
    //如果在上传中，不允许点击
    if (ApplicationDelegate.upDataLoadingBtn) {
        [SVProgressHUD showErrorWithStatus:@"正在上传中，请稍后…"];
        return;
    }
    
    if (self.contentTextView.text.length<1) {
        [SVProgressHUD showErrorWithStatus:@"请输入文字"];
        return;
    }
    
    //    if (self.images.count==0) {
    //        if (self.productTypeId) {
    //            [SVProgressHUD showErrorWithStatus:@"最少留下一张图片"];
    //        }else{
    //            [SVProgressHUD showErrorWithStatus:@"请选择图片"];
    //        }
    //        return;
    //    }
    
    //    if (self.textFieldPrize.text.length<1) {
    //        [SVProgressHUD showErrorWithStatus:@"请输入商品价格"];
    //        return;
    //    }
    
    if (self.productTypeId) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定保存修改？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alertView.tag = 2;
        [alertView show];
        return;
    }
    
    if (sender!=nil&&self.images.count>0) {
        self.timeString=[CurrentDate getCurrentTimeString];
        if (paramDict==nil) {
            paramDict = [NSMutableDictionary new];
        }
        
        
        NSMutableArray * arr = [@[]mutableCopy];
        if (self.images.count > 0) {
            for (int i=0; i<self.images.count; i++) {
                NSDictionary *dict=self.images[i];
                [arr addObject:dict[@"image"]];
            }
        }
        
        
        if (self.switchAskBuy.isOn) {
            ApplicationDelegate.sendImageDict =  @{@"contentTextView":self.contentTextView.text,
                                                   @"nameTextField":@"",
                                                   @"directoryString":self.directoryString,
                                                   @"saleType":@"1"
                                                   };
        }else{
            ApplicationDelegate.sendImageDict =  @{@"contentTextView":self.contentTextView.text,
                                                   @"nameTextField":@"",
                                                   @"directoryString":self.directoryString,
                                                   @"saleType":@"0"
                                                   };
        }
        
        NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
        [paramDict ql_setObject:ui[@"ID"] forKey:@"userId"];
        [paramDict setObject:self.contentTextView.text forKey:@"description"];
        NSString *productName = [[NSDate date] ql_ToStringWithFormat:@"yyyyMMdd_HHmmss"];
        [paramDict setObject:[NSString stringWithFormat:@"%@__%d",productName,[self getRandomNumber:1 to:10000]] forKey:@"productName"];
        [paramDict setObject:self.directoryString forKey:@"pkgId"];
        
        [paramDict setObject:[NSNumber numberWithInt:[self.textFieldPrize.text intValue]] forKey:@"price"];
        if (arr.count > 0) {
            
            [paramDict setObject:arr forKey:@"imageArray"];
        }
        if (self.recorderLength>0) {
            [paramDict ql_setObject:QLIntToNumber(self.recorderLength) forKey:@"tLong"];
        }
        
        [paramDict setObject:self.timeString forKey: @"createDate"];
        if (self.switchAskBuy.isOn){
            [paramDict setObject:@"1" forKey:@"saleType"];
        }else{
            [paramDict setObject:@"0" forKey:@"saleType"];
        }
    }else{
        [SVProgressHUD showErrorWithStatus:@"请选择图片"];
        return;
    }
    
    NSMutableArray * nameArr = [@[]mutableCopy];
    if (self.images.count > 0) {
        for (int i=0; i<self.images.count; i++) {
            NSDictionary *dict=self.images[i];
            [nameArr addObject:dict[@"name"]];
        }
        
    }
    
    //发送到后台
    [ApplicationDelegate sendImageWithImage:paramDict andName:nameArr];
    
    self.contentTextView.text=@"";
    self.textFieldPrize.text=@"";
    self.images=[NSMutableArray array];
    [self.collectionView reloadData];
}

- (void)uploadRecord:(NSMutableDictionary*)dic
{
    [QLMaskUtil showMaskLoadingWithView:self.view];
    
    NSString *fileName = [NSString stringWithFormat:@"%d.spx",[self getRandomNumber:10000 to:100000]];
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ping.vsmu.cn/app/upload-product-tone"]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:1000];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [dic allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"file.file"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[dic objectForKey:key]];
        }
    }
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    [body appendFormat:@"Content-Disposition: form-data; name=\"file.file\"; filename=\"%@\"\r\n",fileName];
    [body appendFormat:@"Content-Type: audio/x-spx\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    NSData *data = [NSData dataWithContentsOfURL:urlPlay];
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    AFURLSessionManager *_manager;
    if (!_manager) {
        _manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    }
    AFHTTPResponseSerializer *serializer = _manager.responseSerializer;
    NSMutableSet *set = [NSMutableSet setWithObjects:@"text/html", nil];
    [set unionSet:serializer.acceptableContentTypes];
    serializer.acceptableContentTypes = set;
    
    NSURLSessionDataTask *task = [_manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
        } else {
            NSDictionary *dic = responseObject;
            if ([dic ql_intForKey:@"code"]==0) {
                self.viewRecord1.hidden = NO;
                self.viewRecord2.hidden = YES;
                if (self.productTypeId) {
                    NSNotification *notification = [NSNotification notificationWithName:@"UPLOAD_SUCCESS" object:@"success"];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                    return;
                }
                
                [self buttonRecordDeleteAction:nil];
            }else{
                [SVProgressHUD showErrorWithStatus:@"上传失败"];
                [QLMaskUtil hideLoadingMaskWithView:self.view];
            }
        }
    }];
    [task resume];
}

- (int)getRandomNumber:(int)from to:(int)to

{
    return (int)(from + (arc4random() % (to - from + 1)));
}
- (void)showResultImages
{
    [self.view.subviews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
        
        if ([obj isKindOfClass:[UIImageView class]]) {
            [obj removeFromSuperview];
        }
    }];
    
    [self.currentSelectedAssetsArray enumerateObjectsUsingBlock:^(GJCFAsset *asset, NSUInteger idx, BOOL *stop) {
        
        NSLog(@"meta:%d",asset.isHaveBeenEdit);
        UIImageView *aImageView = [[UIImageView alloc]initWithImage:asset.thumbnail];
        aImageView.frame = (CGRect){0,100+idx*aImageView.frame.size.width+(idx+1)*3,aImageView.frame.size.width,aImageView.frame.size.height};
        [self.view addSubview:aImageView];
        
    }];
}

#pragma - mark  选择图片
- (IBAction)buttonAddImageAction:(id)sender
{
//    [self openAction:nil];  //bei 1125
   // [self pickAssets:nil];
    GJCFAssetsPickerViewController *assetsPicker = [[GJCFAssetsPickerViewController alloc]init];
    assetsPicker.mutilSelectLimitCount = 8;
    assetsPicker.pickerDelegate = self;
    
    /* 注入自定义相册Cell */
    [assetsPicker registAlbumsCustomCellClass:[CustomAlbumsCell class] withCellHeight:65.f];
    
    /* 注入预先设置的风格 */
    [assetsPicker setCustomStyleByKey:@"DeepCustomStyle"];
    
    [self presentViewController:assetsPicker animated:YES completion:nil];
}
#pragma mark - assetsPicker delegate
- (void)pickerViewController:(GJCFAssetsPickerViewController *)pickerViewController didReachLimitSelectedCount:(NSInteger)limitCount
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"超过限制%d张数",limitCount] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)pickerViewControllerRequirePreviewButNoSelectedImage:(GJCFAssetsPickerViewController *)pickerViewController
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"请选择要预览的图片"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)pickerViewController:(GJCFAssetsPickerViewController *)pickerViewController didFaildWithErrorMsg:(NSString *)errorMsg withErrorType:(GJAssetsPickerErrorType)errorType
{
    if (errorType == GJAssetsPickerErrorTypePhotoLibarayChooseZeroCountPhoto) {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:errorMsg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}
- (void)pickerViewController:(GJCFAssetsPickerViewController *)pickerViewController didFinishChooseMedia:(NSArray *)resultArray
{
    [self.currentSelectedAssetsArray removeAllObjects];
    [self.currentSelectedAssetsArray addObjectsFromArray:resultArray];
//    UIImageView *aImageView = [[UIImageView alloc]initWithImage:asset.thumbnail];
    if (resultArray.count>0) {
        for (int i=0; i<resultArray.count; i++) {
            GJCFAsset *asset=[[GJCFAsset alloc]init];
            asset=resultArray[i];
            
            UIImageView *aImageView = [[UIImageView alloc]initWithImage:asset.fullResolutionImage];
            
            NSString *fileName = asset.fileName;
            UIImage *ima=[[UIImage alloc]init];
            ima=aImageView.image;
//            [self.images addObject:aImageView.image];
            [self.images addObject:@{@"image": aImageView.image,@"name":fileName}];
        }
    }
    [self.collectionView reloadData];
    
//    NSLog(@"array==%@",_currentSelectedAssetsArray);
//    [self showResultImages];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)pickerViewControllerPhotoLibraryAccessDidNotAuthorized:(GJCFAssetsPickerViewController *)pickerViewController
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"请授权访问你的相册"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)pickAssets:(id)sender
{

}

- (IBAction)buttonSelectTypeAction:(id)sender
{
    UIActionSheet *sheet = [[UIActionSheet alloc] init];
    sheet.title = @"分类";
    sheet.delegate = self;
    for (NSDictionary *dic in self.directorys) {
        [sheet addButtonWithTitle:dic[@"NAME"]];
    }
    [sheet addButtonWithTitle:@"取消"];
    sheet.tag = 100;
    [sheet showInView:self.view];
}

- (void)loadTypes
{
    
    
    [QLMaskUtil showMaskLoadingWithView:self.view];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSString *str = [NSString stringWithFormat:@"http://ping.vsmu.cn/app/Interface/Package?type=1018&userId=%@",ApplicationDelegate.currentUserId];
    [requestManager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        if (responseObject) {

            self.directorys = responseObject[@"PACKAGE_RSP"][@"PACKAGE"];
            self.directoryString=self.directorys[0][@"ID"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        
    }];
}

- (void)buttonDeleteAction:(id)sender
{
    UIButton *button = sender;
    NSDictionary *dic = [self.images objectAtIndex:button.tag];
    [self.images removeObject:dic];
    [self.collectionView reloadData];
}

-(void)exitHomePage
{
 //   [self dismissViewControllerAnimated:YES completion:nil];
//    if (self.productInfo) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }else{
//     //   [ApplicationDelegate.ddVC showLeftController:YES];
//        [self.navigationController popViewControllerAnimated:YES];
//    }
    
    // 1. 拿到Window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    // 禁用交互功能
    window.userInteractionEnabled = NO;
    
    // 2.执行退出动画
    [UIView animateWithDuration:0.3 animations:^{
        self.view.y = window.bounds.size.height;
        
    } completion:^(BOOL finished) {
        
        [self.view endEditing:YES];
        // 隐藏控制器的view
        self.view.hidden = YES;

        // 开启交互
        window.userInteractionEnabled = YES;
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex<self.directorys.count) {
        NSDictionary *dic = [self.directorys objectAtIndex:buttonIndex];
        [self.buttonType setTitle:dic[@"NAME"] forState:UIControlStateNormal];
        self.directoryString = dic[@"ID"];
    }
}



#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeMake(72, 72);
    return size;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 2;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.productTypeId) {
        return self.images.count;
    }
    NSLog(@"section个数：%lu",(unsigned long)self.images.count);
     return self.images.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TRImageItemCollectionViewCell *cell = [collectionView  dequeueReusableCellWithReuseIdentifier:@"TRImageItemCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.row>=self.images.count) {
        cell.info = nil;
      //  [cell.buttonAdd addTarget:self action:@selector(buttonAddImageAction:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        cell.info = [self.images objectAtIndex:indexPath.row];
//        cell.imageViewIcon.image = [self.images objectAtIndex:indexPath.row];
        cell.buttonDelete.tag = indexPath.row;
        [cell.buttonDelete addTarget:self action:@selector(buttonDeleteAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        
    
}

#pragma mark -UICollectionViewDataSource_Draggable
- (BOOL)collectionView:(LSCollectionViewHelper *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=self.images.count) {
        return NO;
    }
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    if (indexPath.row>=self.images.count||toIndexPath.row>=self.images.count) {
        return NO;
    }
    return YES;
}

- (void)collectionView:(LSCollectionViewHelper *)collectionView moveItemAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    NSDictionary *dic = [self.images objectAtIndex:fromIndexPath.row];
    [self.images removeObjectAtIndex:fromIndexPath.row];
    [self.images insertObject:dic atIndex:toIndexPath.row];
}

#pragma mark - record
- (IBAction)buttonRecordPlayAction:(id)sender
{
    if (self.isRecording) {
        return;
    }
    if ( ! self.isPlaying) {
        [OggPlayerManager sharedManager].delegate = nil;
        
        self.isPlaying = YES;
        NSString *path = [urlPlay.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        [[OggPlayerManager sharedManager] playAudioWithFileName:path delegate:self];
    }
    else {
        self.isPlaying = NO;
        [[OggPlayerManager sharedManager] stopPlaying];
    }
}

- (IBAction)buttonRecordDownAction:(id)sender
{
    if (timer) {
        [timer invalidate];
        timer = nil;
    }

    [self startRecord];
    
    //设置定时检测
    timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
    self.imageView.hidden = NO;
    self.labelRecordHint.hidden = NO;
}

- (IBAction)buttonRecordUpAction:(id)sender
{
    [self stopRecord];
    [timer invalidate];
    timer = nil;
    self.imageView.hidden = YES;
    self.labelRecordHint.hidden = YES;
}

- (IBAction)buttonRecordDeleteAction:(id)sender
{
    //删除录制文件
    NSFileManager *fm=[NSFileManager defaultManager];
    [fm removeItemAtPath:urlPlay.absoluteString error:nil];
    [timer invalidate];
    timer = nil;
    self.viewRecord2.hidden = YES;
}

- (void)detectionVoice
{
//    [recorder updateMeters];//刷新音量数据
//    //获取音量的平均值  [recorder averagePowerForChannel:0];
//    //音量的最大值  [recorder peakPowerForChannel:0];
//    
//    double lowPassResults = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
//    NSLog(@"%lf",lowPassResults);
//    //最大50  0
//    //图片 小-》大
//    if (0<lowPassResults<=0.06) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_01.png"]];
//    }else if (0.06<lowPassResults<=0.13) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_02.png"]];
//    }else if (0.13<lowPassResults<=0.20) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_03.png"]];
//    }else if (0.20<lowPassResults<=0.27) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_04.png"]];
//    }else if (0.27<lowPassResults<=0.34) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_05.png"]];
//    }else if (0.34<lowPassResults<=0.41) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_06.png"]];
//    }else if (0.41<lowPassResults<=0.48) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_07.png"]];
//    }else if (0.48<lowPassResults<=0.55) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_08.png"]];
//    }else if (0.55<lowPassResults<=0.62) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_09.png"]];
//    }else if (0.62<lowPassResults<=0.69) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_10.png"]];
//    }else if (0.69<lowPassResults<=0.76) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_11.png"]];
//    }else if (0.76<lowPassResults<=0.83) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_12.png"]];
//    }else if (0.83<lowPassResults<=0.9) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_13.png"]];
//    }else {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_14.png"]];
//    }
}
- (void)show
{
    // 1. 拿到Window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    // 2. 设置当前控制器的frame
    self.view.frame = window.bounds;
    // 3. 将当前控制器的view添加到Window上
    [window addSubview:self.view];
    self.view.hidden = NO;
    
    // 禁用交互功能
   // window.userInteractionEnabled = NO;
    
    // 4.执行动画, 让控制器的view从下面转出来
    self.view.y = window.bounds.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        // 执行动画
        self.view.y = 0;
    } completion:^(BOOL finished) {
        // 开启交互
        window.userInteractionEnabled = YES;

    }];
}
- (void)updateImage
{
    [self.imageView setImage:[UIImage imageNamed:@"record_animate_01.png"]];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==1) {
        if (buttonIndex==1) {
            [self deleteProduct];
        }
    }else{
        if (buttonIndex==1) {
            [self saveDesecration];
        }
    }
}

-(void)deleteProduct{
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/Product?type=2006&userId=%@&ID=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,[ui ql_stringForKey:@"ID"],self.productTypeId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        [SVProgressHUD showImage:nil status:@"成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

- (void)saveDesecration
{
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/Product?type=2007&userId=%@&ID=%@&PRICE=%@&DESCRIPTION=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,[ui ql_stringForKey:@"ID"],self.productTypeId,@"0",self.contentTextView.text];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        //系统自带JSON解析
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        if ([QLPublic isSuccess:resultDic]
            ) {
            [self savePhotos];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

- (void)savePhotos
{
    NSMutableArray *arrUrl = [NSMutableArray new];
    NSMutableArray *arrLocal = [NSMutableArray new];
    for (NSDictionary *dic in self.images) {
        if ([dic ql_hasObjectForKey:@"CODE"]) {
            [arrUrl addObject:dic];
        }else if ([dic ql_hasObjectForKey:@"image"]){
            [arrLocal addObject:dic];
        }
    }
    for (NSDictionary *dic in self.imagesService) {
        int code = [dic ql_intForKey:@"CODE"];
        for (NSDictionary *tmp in arrUrl) {
            if (code==[tmp ql_intForKey:@"CODE"]) {
                [self.photoUpdates addObject:dic];
            }else{
                [self.photoDeletes addObject:dic];
            }
        }
    }
    [self.photoUploads addObjectsFromArray:arrLocal];
    [self doPhotos];
}

- (void)doPhotos
{
    if (self.photoDeletes&&self.photoDeletes.count>0) {
        NSDictionary *dic = [self.photoDeletes firstObject];
        [self deletePhotoWithPhotoId:[dic ql_stringForKey:@"CODE"]];
        [self.photoDeletes removeObjectAtIndex:0];
    }else if(self.photoUpdates&&self.photoUpdates.count>0){
        NSDictionary *dic = [self.photoUpdates firstObject];
        int index = 0;
        for (NSDictionary *tmp in self.images) {
            if ([dic ql_intForKey:@"CODE"]==[tmp ql_intForKey:@"CODE"]) {
                break;
            }
            index++;
        }
        [self updateSortWithPhotoId:[dic ql_stringForKey:@"CODE"] index:index];
        [self.photoUpdates removeObjectAtIndex:0];
    }else if(self.photoUploads&&self.photoUploads.count>0){
        self.timeString=[self.productInfo ql_stringForKey:@"CREATE_DATE"];
        if (paramDict==nil) {
            paramDict = [NSMutableDictionary new];
        }
        NSMutableArray * arr = [@[]mutableCopy];
        for (int i=0; i<self.photoUploads.count; i++) {
            NSDictionary *dict=self.photoUploads[i];
            [arr addObject:dict[@"image"]];
        }
        
        
        ApplicationDelegate.sendImageDict =  @{@"contentTextView":self.contentTextView.text,
                                               @"nameTextField":@"",
                                               @"directoryString":self.directoryString,
                                               
                                               };
        NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
        [paramDict ql_setObject:ui[@"ID"] forKey:@"userId"];
        [paramDict setObject:self.contentTextView.text forKey:@"description"];
        [paramDict setObject:self.productNameOld forKeyedSubscript:@"productName"];
        [paramDict setObject:self.directoryString forKey:@"pkgId"];
        [paramDict setObject:self.productTypeId forKey:@"productId"];
        
        [paramDict setObject:[NSNumber numberWithInt:[self.textFieldPrize.text intValue]] forKey:@"price"];
        [paramDict setObject:arr forKey:@"imageArray"];
        [paramDict setObject:self.timeString forKey: @"createDate"];
        
        NSMutableArray * nameArr = [@[]mutableCopy];
        for (int i=0; i<self.photoUploads.count; i++) {
            NSDictionary *dict=self.photoUploads[i];
            [nameArr addObject:dict[@"name"]];
        }
        //发送到后台
        [ApplicationDelegate sendImageWithImage:paramDict andName:nameArr];
        [QLMaskUtil showMaskLoadingWithView:self.view];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)deletePhotoWithPhotoId:(NSString*)pid
{
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/Product?type=2004&userId=%@&ID=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,[ui ql_stringForKey:@"ID"],pid];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        if ([QLPublic isSuccess:resultDic]
            ) {
            [self doPhotos];
        }else{
            [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [operation start];
}

- (void)updateSortWithPhotoId:(NSString*)pid index:(int)index
{
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/Product?type=2008&userId=%@&ID=%@&ORDINAL=%d";
    URLTmp = [NSString stringWithFormat:URLTmp,[ui ql_stringForKey:@"ID"],pid,(index+1)];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        if ([QLPublic isSuccess:resultDic]
            ) {
            [self doPhotos];
        }else{
            [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [operation start];
}

#pragma mark - Recording & Playing Delegate
- (void)recordingFinishedWithFileName:(NSString *)filePath time:(NSTimeInterval)interval {
    self.isRecording = NO;
    urlPlay = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",filePath]];
}

- (void)recordingTimeout {
    self.isRecording = NO;
}

- (void)recordingStopped {
    self.isRecording = NO;
}

- (void)recordingFailed:(NSString *)failureInfoString {
    self.isRecording = NO;
}

- (void)levelMeterChanged:(float)levelMeter {
}

- (void)playingStoped {
    self.isPlaying = NO;
    [SVProgressHUD showSuccessWithStatus:@"播放完成"];
}
#pragma mark ----- AGImageViewController方法

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

#pragma mark - Public methods

- (void)openAction:(id)sender
{
    // Show saved photos on top
    self.ipc.shouldShowSavedPhotosOnTop = NO;
    self.ipc.shouldChangeStatusBarStyle = YES;
    self.ipc.selection = self.images;
    self.ipc.maximumNumberOfPhotosToBeSelected = 9;
    
    // Custom toolbar items
    AGIPCToolbarItem *selectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"选择所有" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
        return YES;
    }];
    AGIPCToolbarItem *flexible = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] andSelectionBlock:nil];
    //    AGIPCToolbarItem *selectOdd = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"+ Select Odd" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
    //        return !(index % 2);
    //    }];
    AGIPCToolbarItem *deselectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"取消所有" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
        return NO;
    }];
    self.ipc.toolbarItemsForManagingTheSelection = @[selectAll, flexible, deselectAll];
    
   // [self addChildViewController:self.ipc];
    
   [self presentViewController:self.ipc animated:YES completion:nil];
 //   [self.navigationController pushViewController:self.ipc animated:YES];
    // Show first assets list, modified by springox(20140503)
    [self.ipc showFirstAssetsController];
    
    //// Show assets list with name, added by springox(20150719)
    //[ipc showAssetsControllerWithName:@"Camera Roll"];
}

#pragma mark - AGImagePickerControllerDelegate

- (NSUInteger)agImagePickerController:(AGImagePickerController *)picker
         numberOfItemsPerRowForDevice:(AGDeviceType)deviceType
              andInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (deviceType == AGDeviceTypeiPad)
    {
        if (UIInterfaceOrientationIsLandscape(interfaceOrientation))
            return 11;
        else
            return 8;
    } else {
        if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
            if (480 == self.view.bounds.size.width) {
                return 6;
            }
            return 7;
        } else
            return 4;
    }
}

- (BOOL)agImagePickerController:(AGImagePickerController *)picker shouldDisplaySelectionInformationInSelectionMode:(AGImagePickerControllerSelectionMode)selectionMode
{
    return (selectionMode == AGImagePickerControllerSelectionModeSingle ? NO : YES);
}

- (BOOL)agImagePickerController:(AGImagePickerController *)picker shouldShowToolbarForManagingTheSelectionInSelectionMode:(AGImagePickerControllerSelectionMode)selectionMode
{
    return (selectionMode == AGImagePickerControllerSelectionModeSingle ? NO : YES);
}

- (AGImagePickerControllerSelectionBehaviorType)selectionBehaviorInSingleSelectionModeForAGImagePickerController:(AGImagePickerController *)picker
{
    return AGImagePickerControllerSelectionBehaviorTypeRadio;
}


@end
